<template>
  <div class="mt-1">
    <van-form>
      <!-- 工厂代码 -->
      <van-field
        v-model="f_value"
        label="工厂代码"
        clickable
        readonly
        arrow-direction="down"
        is-link
        :value="f_value"
        placeholder="请选择工厂代码"
        @click="showPicker_f = true"
      >
      </van-field>
      <!-- 弹出层 -->
      <van-popup v-model="showPicker_f" round position="bottom">
        <van-picker
          title="工厂代码"
          show-toolbar
          :columns="plantcode"
          @cancel="showPicker_f = false"
          @confirm="onAffirm"
        />
      </van-popup>

      <!-- 类型 -->
      <van-field
        v-model="value"
        label="类型"
        clickable
        readonly
        arrow-direction="down"
        is-link
        :value="value"
        placeholder="请选择类型"
        @click="showPicker = true"
      >
      </van-field>
      <!-- 弹出层 -->
      <van-popup v-model="showPicker" round position="bottom">
        <van-picker
          title="类型"
          show-toolbar
          :columns="kind"
          @cancel="showPicker = false"
          @confirm="onConfirm"
        />
      </van-popup>
      <van-field
        v-model="code"
        clearable
        label="拍码"
        ref="code"
        @focus="focus"
        placeholder="请扫描拍码"
      />
      <ag-grid-vue
        style="width: 100%; height: 55vh"
        class="ag-theme-alpine mt-1"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :gridOptions="gridOptions"
        rowSelection="single"
        :rowData="rowData"
      >
      </ag-grid-vue>
      <!-- <van-row type="flex" justify="center">
        <van-button type="info" class="mt-1" block @click="onSubmit"
          >提交</van-button
        >
      </van-row> -->
      <div class="btn">
        <van-col span="7">
          <van-button type="danger" class="mt-1" @click="onRemoveSelected" block
            >删除</van-button
          ></van-col
        >
        <van-col span="7"
          ><van-button type="warning" class="mt-1" @click="updateNum" block
            >修改数量</van-button
          ></van-col
        >
        <van-col span="7"
          ><van-button type="info" class="mt-1" @click="onSubmit" block
            >提交</van-button
          ></van-col
        >
      </div>

      <van-popup
        v-model="ShowStatue"
        position="bottom"
        style="height: 100%"
        class="bg-default"
      >
        <show-send-data :ShowDataB="ShowData" @get-val="Sure" />
      </van-popup>
    </van-form>
    <!-- 修改数量的弹窗提示 -->
    <van-dialog
      v-model="ifShowUpdateNum"
      title="请输入要修改的数量"
      show-cancel-button
      @confirm="SureUpdate"
    >
      <van-field v-model="originNum" label="原始类型" readonly />
      <!-- <div>原始数量:{{ originNum }}</div> -->
      <van-field
        v-model="needUpdateNum"
        type="number"
        placeholder="请输入数量"
      />
    </van-dialog>
  </div>
</template>

<script>
import { AgGridVue } from "ag-grid-vue";
import { InformationSubmit, getDetail } from "../assets/api/post";
import { getStockAdjust, getpickplant } from "../assets/api/get";
import { parseQRCode, toast } from "../untils/commion";
import ShowSendData from "../components/ShowSendDate.vue";
import { AgGrid } from "../minx/AgGrid";

export default {
  components: { AgGridVue, ShowSendData },
  mixins: [AgGrid],
  data() {
    return {
      needUpdateNum: "", //修改后存放数据
      ifShowUpdateNum: false, //修改数量弹窗
      selectDate: [], //选中的行数据
      titles: new Map().set(11, "数量调整"),
      type: null,
      code: "",
      f_value: "CN01",
      value: "",
      ShowStatue: false,
      showPicker_f: false,
      showPicker: false,
      fieldNames: {
        text: "name",
        value: "id",
      },
      columnDefs: [
        { headerName: "物料", field: "productid", flex: 1.5 },
        { headerName: "拍号", field: "uniqueid", flex: 2 },
        { headerName: "数量", field: "stockquantity", flex: 1.5 },
      ],
      plantcode: [],
      copyplantcode: [],
      rowData: [],
      StockStatus: [],
      kind: [],
      detailData: [],
      ShowData: {}, //展示的数据
      originNum: "", //选中的记录的原始数量
      OperatorType: "",
      moveTypeValue: "",
    };
  },
  watch: {
    code(newValue) {
      // if (this.rowData.length == 0 || this.rowData == 1) {
      if (this.f_value && this.value) {
        if (newValue.length > 9) {
          let paresqrdata = parseQRCode(newValue);
          if (paresqrdata) {
            if (
              !this.rowData.find((it) => it.uniqueid == paresqrdata.palletNo)
            ) {
              this.getDetailInfo(paresqrdata.palletNo);
              paresqrdata = "";
              this.code = "";
            } else {
              toast("拍码重复");
              this.code = "";
            }
          } else {
            toast("请检查信息是否完整");
            this.code = "";
          }
        }
        //获取数据
      } else {
        toast("请选择工厂和类型");
      }
      this.code = "";
      // } else {
      //   this.$toast("一次只能修改一条数据");
      //   this.code = "";
      // }
    },
  },
  methods: {
    // 获取焦点时触发的方法
    focus() {
      // 获取焦点时阻止键盘弹出
      this.$refs.code.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.code.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    setTitle() {
      let res = this.titles.get(this.type);
      this.$store.commit("SET_NAVIGATION", res);
    },
    onAffirm(f_value) {
      this.f_value = f_value;
      this.showPicker_f = false;
    },
    onConfirm(value) {
      this.value = value;
      this.showPicker = false;
      this.StockStatus.forEach((item) => {
        if (item.MoveTypeName == this.value) {
          this.moveTypeValue = item.MoveType;
        }
      });
      if (this.value == "908 盘亏到可用库存(Stock Counting U-)") {
        this.OperatorType = "D";
      } else {
        this.OperatorType = "I";
      }
    },
    //删除选中
    onRemoveSelected() {
      let selectedData = this.gridApi.getSelectedRows();
      if (this.rowData[0] == null) {
        this.$toast("当前表格为空");
      } else {
        if (selectedData[0] == null) {
          this.$toast("请选择要删除的数据");
        } else {
          let selctIndex = this.gridApi.applyTransaction({
            remove: selectedData,
          });
          // 删除选中的数据
          this.rowData.splice(selctIndex.remove[0].childIndex, 1);
          this.detailData.splice(selctIndex.remove[0].childIndex, 1);
        }
      }
    },
    //状态数组
    getStatus() {
      this.StockStatus.map((item) => {
        this.kind.push(item.MoveTypeName);
      });
      for (var j in this.kind) {
        if (this.kind.indexOf(this.kind[j]) == -1) {
          this.kind.push(this.kind[j]);
        }
      }
    },
    //工厂代码数组
    getPlantCode(PL) {
      for (var i in PL) {
        this.copyplantcode.push(PL[i].plantcode);
      }
      for (var j in this.copyplantcode) {
        if (this.plantcode.indexOf(this.copyplantcode[j]) == -1) {
          this.plantcode.push(this.copyplantcode[j]);
        }
      }
    },
    //获取后台信息放入表格
    async getDetailInfo(val) {
      let res = await getDetail(val);

      if (res.status == 200) {
        this.ShowStatue = true;
        this.ShowData = JSON.parse(JSON.stringify(res.data[0]));
        // console.log(this.ShowData);
        if (this.ShowData) {
          this.rowData.push(res.data[0]);
        }
        // console.log(res);
      } else {
        toast(res.msg);
      }
      this.code = "";
    },
    //传回来把组件关闭
    Sure() {
      setTimeout(() => {
        this.ShowStatue = false;
      }, 100);
      this.getOther();
    },
    //主列表数据
    getOther() {
      this.detailData.push({
        UniqueId: this.ShowData.uniqueid,
        ProductId: this.ShowData.productid,
        ActSumBox_Before: this.ShowData.stockquantity,
        ActSumBox_After: this.ShowData.stockquantity,
        SortCode: "1",
      });
    },
    //获取当前的日期
    getNowDate() {
      let now = new Date();
      let year = now.getFullYear(); //年
      let month = now.getMonth() + 1; //月
      let day = now.getDate(); //日
      return `${year}-${month}-${day}`;
    },
    //提交
    async onSubmit() {
      if (this.rowData.length == 0) {
        this.$toast("当前表格为空");
      } else {
        let type = "StockAdjust";
        let submit = {
          CreatedName: JSON.parse(localStorage.getItem("username")),
          Plant: this.f_value,
          MoveType: this.moveTypeValue,
          MoveTypeName: this.value,
          AccountDate: this.getNowDate(),
          BillNO: "",
          WareHouseId: "",
          InventoryStatus: this.ShowData.inventorystatus,
          OperatorType: this.OperatorType,
          Comment: "",
          OperatorStatus: "",
          CreatedId: JSON.parse(localStorage.getItem("userid")),
          CreatedOn: "",
          CNN: "",
          ModifiedName: "",
          ModifiedOn: "",
          WareHouseName: "",
        };
        let res = await InformationSubmit(
          type,
          JSON.stringify(submit),
          JSON.stringify(this.detailData)
        );
        if (res.d.state == "success") {
          this.rowData = [];
          this.detailData = [];
          if (this.rowData.length == 0) {
            toast(res.d.message);
          }
        } else {
          toast(res.d.message);
        }
      }
    },
    //自动获取工厂信息
    async getBusinessInfo() {
      let res = await getpickplant();
      if (res.status == 200) {
        this.plant = res.data.data;
        this.getPlantCode(this.plant);
      } else {
        toast("后台发生错误，请与管理员联系");
      }
    },
    //自动获取类型
    async getStockInfo() {
      let res = await getStockAdjust();
      if (res.data.state == "success") {
        this.StockStatus = res.data.data;
        this.getStatus();
      } else {
        toast("后台发生错误，请与管理员联系");
      }
    },
    //点击弹出修改数量弹窗
    updateNum() {
      this.selectDate = this.gridApi.getSelectedRows();
      if (this.selectDate[0] == null) {
        this.$toast("请选择要修改的数据");
      } else {
        this.detailData.forEach((item) => {
          if (this.selectDate[0].uniqueid == item.UniqueId) {
            this.originNum = item.ActSumBox_Before;
          }
        });
        this.ifShowUpdateNum = true;
      }
    },
    // 修改数量确认按钮
    SureUpdate() {
      if (this.needUpdateNum == "" || this.needUpdateNum == 0) {
        this.$toast("未输入数量无法修改");
        this.needUpdateNum = "";
      } else {
        if (this.value == "908 盘亏到可用库存(Stock Counting U-)") {
          if (Number(this.needUpdateNum) > this.originNum) {
            this.$toast("移动类型为盘亏，当前修改无效");
            this.needUpdateNum = "";
          } else {
            this.selectDate[0].stockquantity = this.needUpdateNum;
            this.gridApi.applyTransaction({ update: this.selectDate });
            this.detailData.forEach((item) => {
              if (this.selectDate[0].uniqueid == item.UniqueId) {
                item.ActSumBox_After = Number(this.needUpdateNum);
              }
            });
            this.needUpdateNum = "";
          }
        }
        //////////////////////////
        if (this.value == "907 盘盈到可用库存(Stock Counting U+)") {
          if (Number(this.needUpdateNum) < this.originNum) {
            this.$toast("移动类型为盘盈，当前修改无效");
            this.needUpdateNum = "";
          } else {
            this.selectDate[0].stockquantity = this.needUpdateNum;
            this.gridApi.applyTransaction({ update: this.selectDate });
            this.detailData.forEach((item) => {
              if (this.selectDate[0].uniqueid == item.UniqueId) {
                item.ActSumBox_After = Number(this.needUpdateNum);
              }
            });
            this.needUpdateNum = "";
          }
        }
      }
    },
    // 关闭enter键
    closeEnter() {
      document.onkeydown = function (e) {
        //捕捉回车事件
        var ev = typeof event != "undefined" ? window.event : e;
        if (ev.keyCode == 13 || event.which == 13) {
          return false;
        }
      };
    },
  },
  mounted() {
    this.type = parseInt(this.$route.params.type);
    this.setTitle();
    this.getBusinessInfo();
    this.getStockInfo();
    this.closeEnter();
  },
};
</script>

<style lang="less" scoped>
.ag-theme-alpine .ag-root-wrapper {
  border-left-width: 0;
  border-right-width: 0;
}
.btn {
  display: flex;
  justify-content: space-evenly;
}
</style>